package com.example.selfcontrol.service.Mongo.impl;


import com.example.selfcontrol.config.Response;
import com.example.selfcontrol.entity.Mongo.MongoArticleInfo;
import com.example.selfcontrol.service.Mongo.ArticleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ArticleInfoServiceImpl implements ArticleInfoService {
    @Autowired
    private MongoTemplate mongoTemplate ;

    @Override
    public Response insertArticleInfo(Long articleId, Long authorId, String Content,
                                      Long articleCategory, Date createtime) {
        MongoArticleInfo articleInfo = new MongoArticleInfo(articleId,authorId,Content,articleCategory,createtime) ;
        try {
            mongoTemplate.insert(articleInfo) ;
        }catch (Exception e) {
            return Response.fail() ;
        }

        return Response.ok() ;
    }

    @Override
    public List<List<MongoArticleInfo>> getInfoIndex() {
        System.out.println("请求了MongoIndex");

        List<List<MongoArticleInfo>> resp = new ArrayList<>() ;
        for(int i = 1 ; i <= 6 ; i++) {
            Query query = new Query() ;
            query.with(PageRequest.of(0,5)) ;
            query.addCriteria(Criteria.where("articleCategory").is(i));
            List<MongoArticleInfo> tmp = mongoTemplate.find(query, MongoArticleInfo.class,"mongoArticleInfo") ;
            resp.add(tmp) ;
        }

        return resp ;
    }

    @Override
    public List<MongoArticleInfo> CategoryPagination(int cid, int pageNum, int pageSize) {
        Query query = new Query() ;
        query.with(PageRequest.of(pageNum,pageSize)) ;
        query.addCriteria(Criteria.where("articleCategory").is(cid));
        List<MongoArticleInfo> tmp = mongoTemplate.find(query, MongoArticleInfo.class,"mongoArticleInfo") ;
        return tmp ;
    }
}
